package com.mars.diancan.controller;

import com.mars.diancan.dto.OrderDTO;
import com.mars.diancan.form.ProductForm;
import com.mars.diancan.pojo.ProductCategory;
import com.mars.diancan.pojo.ProductInfo;
import com.mars.diancan.service.ProductCategoryService;
import com.mars.diancan.service.ProductInfoService;
import com.mars.diancan.utils.KeyUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.validation.Valid;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 卖家端商品controller
 * @author MARS
 * @date 2018/7/8
 */
@Controller
@RequestMapping("/seller/product")
public class SellerProductController {

    @Autowired
    private ProductInfoService productInfoService;
    @Autowired
    private ProductCategoryService productCategoryService;

    @GetMapping("/list")
    public ModelAndView list(@RequestParam(value = "page",defaultValue = "1") Integer page,
                             @RequestParam(value = "size",defaultValue = "3") Integer size,
                             Map<String,Object> map){

        PageRequest pageRequest = new PageRequest(page - 1,size);
        Page<ProductInfo> productInfoPage = productInfoService.findAll(pageRequest);

        productInfoPage.getContent();
        // 查询结果输出
        map.put("productInfoPage",productInfoPage);
        // 当前页
        map.put("currentPage",page);
        // 每页显示数据数量
        map.put("size",size);
        // ModelAndView:第一个参数为：模板，第二个参数为：需要向模板传入的数据
        return new ModelAndView("product/list",map);

    }

    /**
     * 商品上架操作
     * @param productId
     * @param map
     * @return
     */
    @GetMapping("/on_sale")
    public ModelAndView onSale(@RequestParam("productId")String productId,Map<String,Object>map){
        try {
            productInfoService.onSale(productId);
        } catch (Exception e) {
            // 失败 ，跳转至失败页面
            map.put("msg",e.getMessage());
            map.put("url","/sell/seller/product/list");
            return new ModelAndView("common/error",map);
        }
        map.put("url","/sell/seller/product/list");
        return new ModelAndView("common/success",map);
    }

    /**
     * 商品下架操作
     * @param productId
     * @param map
     * @return
     */
    @GetMapping("/off_sale")
    public ModelAndView offSale(@RequestParam("productId")String productId,Map<String,Object>map){
        try {
            productInfoService.offSale(productId);
        } catch (Exception e) {
            // 失败 ，跳转至失败页面
            map.put("msg",e.getMessage());
            map.put("url","/sell/seller/product/list");
            return new ModelAndView("common/error",map);
        }
        map.put("url","/sell/seller/product/list");
        return new ModelAndView("common/success",map);
    }

    /**
     * 新增商品
     * @param productId 非必需
     * @param map
     */
    @GetMapping("/index")
    public ModelAndView index(@RequestParam(value ="productId",required = false )String productId,Map<String,Object>map){
        // 如果productId 不为空，则查询商品
        if (!StringUtils.isEmpty(productId)){
            ProductInfo productInfo = productInfoService.findOne(productId);
            map.put("productInfo",productInfo);
        }

        // 查询所有的类目
        List<ProductCategory> categoryList =  productCategoryService.findAll();
        map.put("categoryList",categoryList);

        return new ModelAndView("product/index",map);
    }

    /**
     * 保存/更新商品
     * 1.创建一个商品表单提交VO
     * 2.表单验证的方法
     * @return
     */
    @PostMapping("/save")
    public ModelAndView save(@Valid ProductForm form,
                             BindingResult bindingResult,
                             Map<String,Object> map){
        // 判断参数是否有误
        if (bindingResult.hasErrors()) {
            map.put("msg",bindingResult.getFieldError().getDefaultMessage());
            map.put("url","/sell/seller/product/index");
            return new ModelAndView("common/error",map);
        }
        ProductInfo productInfo = new ProductInfo();
        try {
            // 数据没有错误，先进行商品的查询，再进行copy,防止出现空copy
            // 更新，先去查询是否有数据
            if (!StringUtils.isEmpty(form.getProductId())) {
                productInfo =  productInfoService.findOne(form.getProductId());
            } else {
                // 若form的productId为空，表示新增
                // 设置 新增 数据的 uuid
                form.setProductId(KeyUtil.genUniqueKey());
                form.setCreateTime(new Date());
                form.setUpdateTime(new Date());
            }

            form.setUpdateTime(new Date());
            BeanUtils.copyProperties(form,productInfo);
            productInfoService.save(productInfo);
        } catch (Exception e) {
            map.put("msg",bindingResult.getFieldError().getDefaultMessage());
            map.put("url","/sell/seller/product/index");
            return new ModelAndView("common/error",map);
        }
        map.put("url","/sell/seller/product/list");
        return new ModelAndView("common/success",map);
    }

}
